package app1.rapidsquare.com.fragment;

import android.app.Activity;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.Toast;

import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshListView;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedList;

import app1.rapidsquare.com.activity.MainActivity;
import app1.rapidsquare.com.adapter.EventsAdapter;
import app1.rapidsquare.com.database.AgileEventsProvider;
import app1.rapidsquare.com.Utility.Utility;
import app1.rapidsquare.com.activity.EventActivity;
import app1.rapidsquare.com.activity.R;
import app1.rapidsquare.com.classes.Events;

public class EventFragment extends AgileFragment {

    private PullToRefreshListView mPullRefreshListView;
    private ListView mActualListView;
    private EventsAdapter mAdapter;
    private PullToRefreshBase.Mode mMode;
    private HashMap<String, Integer> eventHistory = new HashMap<String, Integer>();

    public static EventFragment newInstance() {
        return new EventFragment();
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setRetainInstance(true);

        if (eventHistory == null)
            eventHistory = new HashMap<String, Integer>();
        mAdapter = new EventsAdapter(getActivity());
    }

    @Override
    public void onResume() {
        super.onResume();
    }

    @Override
    public void onPause() {
        super.onPause();
    }


    @Override
    protected void getResponce(String jsonResult) {
        if (!Utility.isNullOrEmpty(jsonResult)) {
            try {
                String result = "";
                JSONObject jObject = new JSONObject(jsonResult);
                if (jObject.has("Error"))
                    result = jObject.getString("Error");
                if (jObject.has("Result"))
                    result = jObject.getString("Result");

                if (result.equals("Waiting"))
                    result = "Your request is sending";

                if (!Utility.isNullOrEmpty(result))
                    Toast.makeText(getActivity(), result,
                            Toast.LENGTH_SHORT).show();

            } catch (JSONException ex) {
                Utility.Log("EventFragment -> getResponce ", ex);
            }
        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {

        View v = inflater.inflate(R.layout.fragment_event, container, false);
        mPullRefreshListView = (PullToRefreshListView) v
                .findViewById(R.id.pull_refresh_list);
        mPullRefreshListView.setMode(PullToRefreshBase.Mode.BOTH);

        mMode = PullToRefreshBase.Mode.PULL_FROM_START;

        if (mPullRefreshListView != null && savedInstanceState == null) {
            mPullRefreshListView.postDelayed(new Runnable() {

                @Override
                public void run() {
                    mPullRefreshListView.setMode(PullToRefreshBase.Mode.PULL_FROM_START);
                    mPullRefreshListView.setRefreshing(true);
                }
            }, 2000);
        }

        mPullRefreshListView
                .setOnRefreshListener(new PullToRefreshBase.OnRefreshListener<ListView>() {

                    @Override
                    public void onRefresh(
                            PullToRefreshBase<ListView> refreshView) {
                        mMode = refreshView.getCurrentMode();

                        boolean isPast = false;
                        int startNumber = 0;
                        if (mMode == PullToRefreshBase.Mode.PULL_FROM_START) {
                            isPast = true;
                            if (eventHistory != null
                                    && eventHistory.containsKey("Past"))
                                startNumber = eventHistory.get("Past");
                        }
                        if (mMode == PullToRefreshBase.Mode.PULL_FROM_END) {
                            isPast = false;
                            if (eventHistory != null
                                    && eventHistory.containsKey("New"))
                                startNumber = eventHistory.get("New");
                        }
                        new GetDataTask(startNumber, isPast).execute();

                    }
                });

        mActualListView = mPullRefreshListView.getRefreshableView();

//        mActualListView.setDivider(null);
        mActualListView.setAdapter(mAdapter);
        mActualListView.setOnItemClickListener(onItemClickListener);
        return v;
    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        try {
            if (savedInstanceState != null
                    && savedInstanceState.containsKey("ScheduleList")) {
                if (savedInstanceState.getSerializable("ScheduleList") instanceof LinkedList) {
                    mAdapter.setEventsList((LinkedList<Events>) savedInstanceState
                            .getSerializable("ScheduleList"));
                }
                if (savedInstanceState.getSerializable("ScheduleListHistore") instanceof HashMap) {
                    eventHistory = (HashMap<String, Integer>) savedInstanceState
                            .getSerializable("ScheduleListHistore");
                }
            }
        } catch (Exception ex) {
            Utility.Log("EventFragment -> onActivityCreated", ex);
        }
    }

    private AdapterView.OnItemClickListener onItemClickListener = new AdapterView.OnItemClickListener() {

        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position,
                                long id) {
            Intent intent = new Intent(getActivity(),
                    EventActivity.class);
            Events event = (Events) mAdapter.getItem(position - 1);
            if (Utility.isNullOrEmpty(event.Header) && !Utility.isNullOrEmpty(event.Room)) {
                intent.putExtra("EventData", event);
                startActivityForResult(intent, Utility.EVENT_DETAILS_ACTIVITY_REQUEST_CODE);
            } else
                return;
        }
    };

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (requestCode == Utility.EVENT_DETAILS_ACTIVITY_REQUEST_CODE && resultCode == Activity.RESULT_OK) {
            Events event = (Events) data.getSerializableExtra("EventData");
            if (event != null) {
                mAdapter.replaceEvent(event);
            }
        }

        if (requestCode == Utility.EVENT_DETAILS_ACTIVITY_REQUEST_CODE && resultCode == Activity.RESULT_FIRST_USER) {
            ((MainActivity) getActivity()).GoToProfileActivityResult(data);
        }
    }

    private synchronized void UpdateEventListAdapter(ArrayList<Events> eventList) {

        if (eventList.size() > 0) {

            boolean isPast = true;
            int startNumber = 0;

            startNumber=EventItemsCount(eventList);

            if (mMode == PullToRefreshBase.Mode.PULL_FROM_START) {
                isPast = true;
                mAdapter.AddPastItems(eventList);
            }
            if (mMode == PullToRefreshBase.Mode.PULL_FROM_END) {
                isPast = false;
                mAdapter.AddLastItems(eventList);
            }



           /* for (Events events : eventList) {
                if (mAdapter.contains(events)
                        && Utility.isNullOrEmpty(events.Header)) {
                    int position = mAdapter.indexOf(events);
                    if (position != -1) {
                        mAdapter.getEventsList().set(position, events);
                    }
                } else {
                    if (mMode == PullToRefreshBase.Mode.PULL_FROM_START) {
                        isPast = true;
                        startNumber=EventItemsCount(eventList)
                        if (Utility.isNullOrEmpty(events.Header)) {
                            mAdapter.addFirstItem(events);
                            startNumber++;
                        } else {
                            mAdapter.removerHeader(events);
                            mAdapter.addFirstSectionHeaderItem(events);
                        }
                    }
                    if (mMode == PullToRefreshBase.Mode.PULL_FROM_END) {
                        isPast = false;
                        if (Utility.isNullOrEmpty(events.Header)) {
                            mAdapter.addLastItem(events);
                            startNumber++;
                        } else {
                            if (!mAdapter.checkHeader(events))
                                mAdapter.addLastSectionHeaderItem(events);
                        }
                    }
                }
            }*/

            if (isPast) {
                int pastEventsCount = 0;
                if (eventHistory.containsKey("Past")) {

                    pastEventsCount = eventHistory.get("Past");
                }

                pastEventsCount += startNumber;

                eventHistory.put("Past", pastEventsCount);

            } else {
                int newEventsCount = 0;

                if (eventHistory.containsKey("New")) {

                    newEventsCount = eventHistory.get("New");
                }

                newEventsCount += startNumber;

                eventHistory.put("New", newEventsCount);
            }

            mAdapter.notifyDataSetChanged();
        }
        if (mPullRefreshListView != null) {
            mPullRefreshListView.setMode(PullToRefreshBase.Mode.BOTH);
            mPullRefreshListView.onRefreshComplete();
        }
    }

    private class GetDataTask extends AsyncTask<Void, Void, ArrayList<Events>> {

        private int mStartNumber;
        private boolean mIsPast;

        public GetDataTask(int startNumber, boolean isPast) {
            mStartNumber = startNumber;
            mIsPast = isPast;
        }

        @Override
        protected ArrayList<Events> doInBackground(Void... params) {
            ArrayList<Events> events = new ArrayList<Events>();

            try {
                AgileEventsProvider mEventsProvider = new AgileEventsProvider(getActivity());
                events = mEventsProvider.SelectWithPaging(mStartNumber,
                        mIsPast);
               /* if (mIsFirstTime && events != null && events.size() == 0) {
                    mIsFirstTime = false;
                    events = mEventsProvider.SelectWithPaging(mStartNumber,
                            !mIsPast);
                }*/

            } catch (Exception e) {
                Utility.Log("Error is loading events in EventFragment", e);
            }

            return events;
        }

        @Override
        protected void onPostExecute(ArrayList<Events> result) {

            UpdateEventListAdapter(result);

            super.onPostExecute(result);
        }
    }

    @Override
    public void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        if (mAdapter != null) {
            outState.putSerializable("ScheduleList", mAdapter.getEventsList());
            outState.putSerializable("ScheduleListHistore", eventHistory);
        }
    }

    private int EventItemsCount(ArrayList<Events> eventList) {
        int eventItemCount = 0;
        for (int i = 0; i < eventList.size(); i++) {
            if (Utility.isNullOrEmpty(eventList.get(i).Header))
                eventItemCount++;
        }

        return eventItemCount;
    }
}
